package com.zzxy.spring2g.factory;

import com.zzxy.spring2g.aspect.MyAspect;
import com.zzxy.spring2g.service.IStudentService;
import com.zzxy.spring2g.service.impl.StudentServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBaanFactory {
  public static IStudentService createStudentService(){
    //1.target class
    StudentServiceImpl studentServiceImpl = new StudentServiceImpl();
    //2.advice
    MyAspect myAspect=new MyAspect();
    //3.weaving
    IStudentService studentServiceProxy = (IStudentService) Proxy.newProxyInstance(MyBaanFactory.class.getClassLoader(), studentServiceImpl.getClass().getInterfaces(), new InvocationHandler() {
      @Override
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        myAspect.before();

        Object obj = method.invoke(studentServiceImpl, args);
        myAspect.after();
        return obj;
      }
    });
    return studentServiceProxy;
  }
}
